<?php
namespace App\Library\Guzzle;

use App\Exceptions\GeneralException;
use App\Library\String\Strings;
use App\Library\Traits\PlatformRequest;
use App\Models\UserAuthSpiderTransLog;
use App\Models\UserInfo;
use App\Models\UserLoanRequest;
use Carbon\Carbon;

class RiskPlatformRequest
{
    use PlatformRequest;
    /**
     * 风控平台基础uri
     * @var \Illuminate\Config\Repository|mixed
     */
    protected $platform_uri;

    /**
     * 发起风控url
     * @var string
     */
    protected $risk_url = 'riskControl/applyRisk';

    /**
     * 查询风控结果
     * @var string
     * */
    protected $risk_result_url = 'riskControl/queryRiskResult';

    /**
     * 开启爬虫
     * @var string
     * */
    protected $start_spider_url = 'datacenter/notice';

    /*
     * 结果集
     * */
    protected $res_info_url = 'riskControl/getUserRiskData';

    /*
     *
     * */
    protected $r360_data_url = 'datacenter/webCrawlerData';

    /*
     * 支付宝详情
     * */
    protected $alipay_spider_url  = 'datacenter/moxie/aliPayInfo';

    /*
     * 运营商详情
     * */
    protected $carrier_spider_url = 'datacenter/mobileInfo';

    /**
     * 公共请求参数
     * @var array
     */
    protected $body = [];

    /**
     * 参数集合
     * @var
     */
    private $_pub_data;

    /**
     * 业务数据签名
     * @var
     */
    private $_pub_sign;

    /**
     * RiskPlatformRequest constructor.
     */
    public function __construct()
    {
        $this->platform_uri = config('common.common_platform_base_uri');
    }


    /**
     * 调用风控系统
     * @author luwei
     * @param $data
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function useRiskSystem($data)
    {
        $this->_pub_data = [
            'bankCardNo' => $data['bankCardNo'],
            'companyName' => $data['companyName'],
            'creditNo' => $data['creditNo'],
            'deviceType' => $data['deviceType'],
            'flowFlag' => $data['flowFlag'],
            'idNo' => $data['idNo'],
            'phone' => $data['phone'],
            'userName' => $data['userName'],
            'certificateInAuthority' => $data['certificateInAuthority'],
            'certificateExpriy' => $data['certificateExpriy'],
            'channel' => $data['channel'],
            'creditApplyTime' => $data['creditApplyTime'],
            'educationBackground' => $data['educationBackground'],
            'deviceId' => $data['deviceId'],
            'faceParam' => $data['faceParam'],
            'tradeNOs' => $data['tradeNOs'],
            'phoneAddress' => $data['phoneAddress'],
            'emergencyContact' => $data['emergencyContact'],
        ];
        foreach ($this->_pub_data['phoneAddress'] as &$v){
            $v['name'] = Strings::specialString($v['name']);
        }
        \Log::debug('申请风控参数：'.json_encode($this->_pub_data,JSON_UNESCAPED_UNICODE));
        $this->_pub_sign = Sign::sign($this->_pub_data, 1);
        $resp = $this->request($this->risk_url, 'common');
        \Log::debug('记录返回数据：'.json_encode($resp,JSON_UNESCAPED_UNICODE));
        return $resp;
    }

    /**
     * 风控结果查询
     * @param $params
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function queryRiskResult($params)
    {
        $this->_pub_data = [
            'riskId' => $params['risk_id']
        ];
        \Log::debug('风控查询参数：'.json_encode($this->_pub_data,JSON_UNESCAPED_UNICODE));
        $this->_pub_sign = Sign::sign($this->_pub_data, 1);
        $resp = $this->request($this->risk_result_url, 'common');
        \Log::debug('记录返回数据：'.json_encode($resp,JSON_UNESCAPED_UNICODE));
        return $resp;
    }

    /**
     * 开启爬虫，获取流水号
     * @param $data
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @author luwei
     * @date 2019-01-05 12:03
     */
    public function getSerialNum($data)
    {
        $this->_pub_data = [
            'name' => $data['name'],
            'certNo' => $data['certNo'],
            'mobile' => $data['mobile'],
            'prodId'=> $data['prodId']
        ];
        \Log::debug('开启爬虫发送数据：'.json_encode($this->_pub_data,JSON_UNESCAPED_UNICODE));
        $this->_pub_sign = Sign::sign($this->_pub_data, 1);
        $resp = $this->request($this->start_spider_url, 'common');
        \Log::debug('记录返回数据：'.json_encode($resp,JSON_UNESCAPED_UNICODE));
        return $resp;
    }

    /**
     * 详情结果
     * @param $data
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @author luwei
     * @date 2019-01-14 11:56
     */
    public function result($data){
        $this->_pub_data = [
            'idNo' => $data['idNo'],
            'phone' => $data['phone']
        ];
        \Log::debug('详情结果查询数据：'.json_encode($this->_pub_data,JSON_UNESCAPED_UNICODE));
        $this->_pub_sign = Sign::sign($this->_pub_data, 1);
        $resp = $this->request($this->res_info_url, 'common');
        \Log::debug('详情结果查询数据：'.json_encode($resp,JSON_UNESCAPED_UNICODE));
        return $resp;
    }

    /**
     * 融360数据
     * @param $params
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function pushSpiderData($params)
    {
        $this->_pub_data = [
            'idNo' => $params['idNo'],
            'phone' => $params['phone'],
            'name' => $params['name'],
            'channel' => $params['channel'],
            'data' => $params['data']
        ];
        if(array_key_exists('type',$params)){
            array_push($this->_pub_data,$params['type']);
        }
        \Log::debug('推送爬虫数据：'.json_encode($this->_pub_data,JSON_UNESCAPED_UNICODE));
        $this->_pub_sign = Sign::sign($this->_pub_data, 1);
        $resp = $this->request($this->r360_data_url, 'common');
        \Log::debug('记录返回数据：'.json_encode($resp,JSON_UNESCAPED_UNICODE));
        return $resp;
    }

    /**
     * @param $data
     * @param string $type
     * @return mixed
     * @throws GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @author luwei
     * @date 2019-03-07 11:12
     */
    public function spiderInfo($data, $type){
        $this->_pub_data = [
            'tradeNo' => $data['tradeNo'],
        ];
        switch ($type){
            case UserAuthSpiderTransLog::TYPE_CARRIER_ENG:
                $url = $this->carrier_spider_url;
                break;
            case UserAuthSpiderTransLog::TYPE_ALIPAY_ENG:
                $url = $this->alipay_spider_url;
                break;
            default:
                throw new \Exception('爬虫数据类型错误');

        }
        \Log::debug('爬虫结果集查询参数：'.json_encode($this->_pub_data,JSON_UNESCAPED_UNICODE));
        $this->_pub_sign = Sign::sign($this->_pub_data, 1);
        $resp = $this->request($url, 'common');
        \Log::debug('爬虫结果集查询数据：'.json_encode($resp,JSON_UNESCAPED_UNICODE));
        return $resp;
    }

    /**
     * 构造风控发送数据
     * @param $loan
     * @param $user
     * @param $params
     * @return array
     * @author luwei
     * @date 2019-01-05 20:48
     * @throws GeneralException
     */
    public function createParams($loan, $user, $params) {
        //银行卡关联信息
        if ($loan->bankCard) {
            $bankCardNum = $loan->bankCard->card_num;
        } else {
            throw new \Exception('请先绑定银行卡信息');
        }

        //流水号
        $tradeNums = $loan->userTransLog;
        $tradeInfo = [];
        $typeArray = [UserAuthSpiderTransLog::TYPE_ALIPAY_ENG,UserAuthSpiderTransLog::TYPE_CARRIER_ENG];
        foreach ($tradeNums as $trade){
            if(in_array($trade->type,$typeArray)){
                $tradeInfo[] = $trade->trade_no;
            }
        }
        if(count($tradeInfo) < 2){
            throw new \Exception('缺少爬虫数据：'.json_encode($tradeInfo,JSON_UNESCAPED_UNICODE));
        }

        //直系联系人
        if ($loan->baseInfo) {
            $userInfo = $loan->baseInfo;
        } else {
            throw new \Exception('请先填写基本信息');
        }
        $directInfo = [
            [
                'name'         => $userInfo->linkman_first,
                'phone'        => $userInfo->linkman_first_phone,
                'relationShip' => $userInfo->linkman_first_relation,
                'remark'       => UserInfo::$USER_RELATION[$userInfo->linkman_first_relation]
            ]
        ];
        //一般联系人
        $generateInfo = [
            [
                'name'         => $userInfo->linkman_second,
                'phone'        => $userInfo->linkman_second_phone,
                'relationShip' => $userInfo->linkman_second_relation,
                'remark'       => UserInfo::$USER_RELATION[$userInfo->linkman_second_relation]
            ]
        ];
        $phoneInfo    = array_merge($generateInfo, $directInfo);
        //通讯录
        $phoneList    = $userInfo->phone_list ?? [];
        $retPhoneList = [];
        foreach ($phoneList as $data) {
            $retPhoneList[] = [
                'phone'  => !empty($data['phone'])?$data['phone']:'',
                'name'   => !empty($data['contactName'])?$data['contactName']:'',
                'remark' => ''
            ];
        }

        //身份证相关信息
        if ($loan->userCert) {
            $cert = [
                "blackBox"               => $loan->userCert->issuing_authority,
                "certificateExpriy"      => $loan->userCert->valid_date_end,
                "certificateInAuthority" => $loan->userCert->issuing_authority,
                "idNo"                   => $loan->userCert->num,
                "userName"               => $loan->userCert->name,
                "homeAddress"            => $loan->userCert->domicile_address
            ];
        } else {
            throw new \Exception('请认证身份证');
        }

        $source = $user->source ?? 0;
        $data = [
            'bankCardNo'          => $bankCardNum,
            'channel'             => (string)$source,
            "companyName"         => optional($loan->baseInfo)->company,
            "creditApplyTime"     => Carbon::parse($loan->apply_time)->format('YmdHis'),
            "creditNo"            => $this->creditNo($loan->trans_id),
            "deviceId"            => (string)$params['device_id'],
            "deviceType"          => UserLoanRequest::$DEVICE_TYPE[$params['device_type']],
            "educationBackground" => $userInfo->edu_str,
            "faceParam"           => "",
            "flowFlag"            => (string)UserInfo::FLOW_FLAG_FULL,
            'emergencyContact'    => $phoneInfo,
            "phone"               => $user->phone_num,
            'phoneAddress'        => $retPhoneList,
            "tradeNOs"            => $tradeInfo,
        ];
        $data = array_merge($data, $cert);
        return $data;
    }

    /**
     * 生成风控授信号
     * @param $num
     * @return string
     * @author luwei
     * @date 2019-01-05 20:48
     */
    private function creditNo($num) {
        if (is_numeric($num)) {
            $string = UserLoanRequest::CREDIT_NO_PREFIX . $num;
            return $string;
        }
    }
}